package com.weiyin.examination.course;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.weiyin.examination.R;
import com.weiyin.examination.adapter.CourseA4Adapter;
import com.weiyin.examination.application.Constant;
import com.weiyin.examination.dialog.CourseA1Dialog;
import com.weiyin.examination.http.RetrofitClient;
import com.weiyin.examination.listener.CourseInterface;
import com.weiyin.examination.listener.DialogResultInterface;
import com.weiyin.examination.listener.DialogShowListener;
import com.weiyin.examination.module.AnswerModule;
import com.weiyin.examination.module.TestModule;
import com.weiyin.examination.util.LayoutHelper;
import com.weiyin.examination.util.LogUtil;
import com.weiyin.examination.util.SPUtil;
import com.weiyin.examination.view.GridLayoutManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author njf
 *         Created by lenovo on 2017/9/18.
 */

public class CourseA4 extends Course implements CourseA4Adapter.OnItemClickInterface {
    private View rootView;
    private Activity activity;
    private ClickAble clickAble;

    private RecyclerView courseA4RecyclerView1;
    private CourseA4Adapter courseA4Adapter1;

    private TextView titleLayoutNextTextView, titleLayoutLastTextView, titleLayoutSubjectContentTextView,
            titleLayoutSubjectScoreTextView, titleLayoutNumberTextView, titleTicketNumber;
    private RelativeLayout titleLayoutNumberRl;
    private ImageView courseA4ImageView1;

    private TestModule testModule;
    private List<TestModule> testModuleList;
    private List<AnswerModule> answerModuleList;
    private int courseIndex;
    private LayoutHelper layoutHelper;
    private Handler mHandler = new Handler();
    private Map<String, String> map;
    private double score;

    @Override
    public void onCreate(Activity activity, ViewFlipper contain, List<TestModule> courseEntities, int index) {
        if (rootView == null) {
            rootView = LayoutInflater.from(activity).inflate(R.layout.coursea4_layout, null);
            layoutHelper = new LayoutHelper(activity);
            layoutHelper.scaleView(rootView);

            contain.addView(rootView);
            this.testModuleList = courseEntities;
            this.activity = activity;
            this.courseIndex = index;
            this.testModule = testModuleList.get(index);
            map = new HashMap<>();
            clickAble = new ClickAble();
            if (testModule != null) {
                if (testModule.getRightAnswerList() != null) {
                    this.answerModuleList = testModule.getRightAnswerList();
                }
            }
            initView();
        }
    }

    @Override
    public void initView() {
        titleLayoutNextTextView = (TextView) rootView.findViewById(R.id.titleLayoutNextTextView);
        titleLayoutLastTextView = (TextView) rootView.findViewById(R.id.titleLayoutLastTextView);
        titleLayoutSubjectContentTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectContentTextView);
        titleLayoutSubjectScoreTextView = (TextView) rootView.findViewById(R.id.titleLayoutSubjectScoreTextView);
        titleLayoutNumberTextView = (TextView) rootView.findViewById(R.id.titleLayoutNumberTextView);
        courseA4ImageView1 = (ImageView) rootView.findViewById(R.id.courseA4ImageView1);
        titleTicketNumber = (TextView) rootView.findViewById(R.id.titleTicketNumber);
        titleLayoutNumberRl = (RelativeLayout) rootView.findViewById(R.id.titleLayoutNumberRl);

        courseA4RecyclerView1 = (RecyclerView) rootView.findViewById(R.id.courseA4RecyclerView);
        courseA4Adapter1 = new CourseA4Adapter(activity, R.layout.coursea4_item_layout, testModule.getSelectionList());
        courseA4RecyclerView1.setLayoutManager(new GridLayoutManager(activity, testModule.getSelectionList().size(), LinearLayoutManager.VERTICAL, false));
        courseA4RecyclerView1.setAdapter(courseA4Adapter1);
        courseA4Adapter1.setOnItemClickInterface(this);

        titleLayoutNextTextView.setOnClickListener(clickAble);
        titleLayoutLastTextView.setOnClickListener(clickAble);
        titleLayoutNumberRl.setOnClickListener(clickAble);
    }

    private void initViewData() {
        if (testModule != null) {
            titleTicketNumber.setText("准考证号：" + "" + testModule.getTickNumber());

            titleLayoutLastTextView.setVisibility(courseIndex == 0 ? View.GONE : View.VISIBLE);
            titleLayoutNextTextView.setVisibility(courseIndex == testModuleList.size() - 1 ? View.GONE : View.VISIBLE);

            titleLayoutSubjectContentTextView.setText((courseIndex + 1) + "丶" + testModule.getSubjectTitle());
            titleLayoutSubjectScoreTextView.setText("（" + testModule.getScore() + "分）");
            titleLayoutNumberTextView.setText("第" + (courseIndex + 1) + "题/第" + (testModuleList.size()) + "题");
            Glide.with(activity).
                    load(RetrofitClient.BASE_URL + testModule.getSubjectUrl()).
                    into(courseA4ImageView1);
        }
    }

    @Override
    public void onItemClick(BaseViewHolder holder, int position) {
        showDialog(holder, position);
    }

    private void showDialog(final BaseViewHolder holder, final int position) {
        CourseA1Dialog courseA1Dialog;
        courseA1Dialog = new CourseA1Dialog(activity, R.style.BlueToothDialogStyle, testModule);
        int x = (int) holder.getView(R.id.courseA4ItemLayout).getX() + holder.getView(R.id.courseA4ItemLayout).getWidth() / 2;
        int y = holder.getView(R.id.courseA4ItemLayout).getBottom() + courseA4RecyclerView1.getTop();
        Window window = courseA1Dialog.getWindow();
        assert window != null;
        WindowManager.LayoutParams p = window.getAttributes();
        Display d = window.getWindowManager().getDefaultDisplay();
        p.x = x - d.getWidth() / 2;
        p.y = y - (d.getHeight() / 2 - layoutHelper.scaleDimension(230 + 150, "y") / 2);
        window.setAttributes(p);
        courseA1Dialog.setDialogResultInterface(new DialogResultInterface() {
            @Override
            public void result(String type, String result, String answerId) {
                if (Constant.CENTER.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA4ItemTextView1, result.substring(0, index) + "\n" + result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA4ItemTextView1, result);
                    }
                    map.put(position + Constant.CENTER, answerId);
                } else if (Constant.LEFT.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA4ItemTextView1, result.substring(0, index) + "\n" + result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA4ItemTextView1, result);
                    }
                    map.put(position + Constant.LEFT, answerId);
                } else if (Constant.RIGHT.equals(type)) {
                    if (result.contains(Constant.INTERVAL_SIGN)) {
                        int index = result.indexOf(Constant.INTERVAL_SIGN);
                        holder.setText(R.id.courseA4ItemTextView2, result.substring(0, index) + "\n" + result.substring(index + 1));
                    } else {
                        holder.setText(R.id.courseA4ItemTextView2, result);
                    }
                    map.put(position + Constant.RIGHT, answerId);
                }

            }
        });
        if (activity.hasWindowFocus()) {
            courseA1Dialog.show();
        }
    }

    class ClickAble implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.titleLayoutNextTextView:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.NEXT_KNOWLEDGE, courseIndex + 1);
                    break;
                case R.id.titleLayoutLastTextView:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    courseInterface.courseInterfaceResult(Constant.LAST_KNOWLEDGE, courseIndex - 1);
                    break;
                case R.id.titleLayoutNumberRl:
                    dialogShowListener.dialogShow(1, courseIndex, resultMap());
                    dialogShowListener.dialogShow(0, courseIndex, resultMap());
                    break;
                default:
                    break;
            }
        }
    }

    private boolean resultMap() {

        Constant.getScreen(activity, SPUtil.getSharedPreferencesData(activity, "number") + "_" + (courseIndex + 1),SPUtil.getSharedPreferencesData(activity, "number")+"_"+ (courseIndex + 1));
        if (map != null) {
            boolean result = false;
            int index = 0;
            score = 0;
            for (int i = 0; i < answerModuleList.size(); i++) {
                if (map.get(i + Constant.CENTER) != null || map.get(i + Constant.LEFT) != null || map.get(i + Constant.RIGHT) != null) {
                    if (map.get(i + Constant.CENTER) != null && map.get(i + Constant.CENTER).equals(answerModuleList.get(i).getCenterId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore());
                    }

                    if (map.get(i + Constant.LEFT) != null && map.get(i + Constant.LEFT).equals(answerModuleList.get(i).getCenterId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore());
                    }

                    if (map.get(i + Constant.RIGHT) != null && map.get(i + Constant.RIGHT).equals(answerModuleList.get(i).getRightId())) {
                        score += Double.valueOf(answerModuleList.get(i).getScore()) / 2;
                    }
                    index++;
                }
            }
            LogUtil.i(TAG, "score=" + score);
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA4.class.getSimpleName(), score + "");
            if (index == answerModuleList.size()) {
                result = true;
            }

            return result;
        } else {
            SPUtil.setSharedPreferencesData(activity.getApplicationContext(), CourseA4.class.getSimpleName(), 0 + "");

            return false;
        }
    }

    @Override
    public void setCourseInterface(CourseInterface courseInterface) {
        this.courseInterface = courseInterface;
    }

    @Override
    public void setCourseDialogListener(DialogShowListener dialogListener) {
        this.dialogShowListener = dialogListener;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void show(List<TestModule> courseEntities, int index, String type) {
        initViewData();
    }

    @Override
    public void stop() {

    }

    @Override
    public void destroy() {

    }
}
